﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace DAO
{
    public abstract class AbstractDAO<P>
    {
        protected string tableName;

        protected abstract string GetTableName();

        protected DataProvider dataProvider;

        public AbstractDAO()
        {
            dataProvider = new DataProvider();
            tableName = GetTableName();
        }

        public P getById(int id)
        {
            P p;
            String query = String.Format("SELECT * FROM {0} WHERE id = '{1}'", tableName, id.ToString());
            DataTable dt = dataProvider.ExecuteQuery(query);
            if (dt.Rows.Count > 0)
            {
                DataRow row = dt.Rows[0];
                p = GetByDataRow(row);
            }
            else
            {
                p = Activator.CreateInstance<P>();
            }
            return p;
        }

        public virtual List<P> GetAll()
        {
            List<P> ls = new List<P>();
            String query = String.Format("SELECT * FROM {0}", tableName);
            DataTable dt = dataProvider.ExecuteQuery(query);
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow r in dt.Rows)
                {
                    P p = GetByDataRow(r);
                    ls.Add(p);
                }
            }
            return ls;
        }

        public virtual List<P> GetAllUnCommited()
        {
            List<P> ls = new List<P>();
            String query = String.Format("exec Proc_Get_{0}", tableName);
            DataTable dt = dataProvider.ExecuteQuery(query);
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow r in dt.Rows)
                {
                    P p = GetByDataRow(r);
                    ls.Add(p);
                }
            }
            return ls;
        }

        public DataTable  GetDataTable()
        {
            String query = String.Format("SELECT * FROM {0}", tableName);
            DataTable dt = dataProvider.ExecuteQuery(query);
            return dt;
        }
        public List<P> GetAllWhere(string where)
        {
            List<P> ls = new List<P>();
            String query = String.Format("SELECT * FROM {0} WHERE {1}", tableName, where);
            DataTable dt = dataProvider.ExecuteQuery(query);
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow r in dt.Rows)
                {
                    P p = GetByDataRow(r);
                    ls.Add(p);
                }
            }
            return ls;
        }


        public abstract P GetByDataRow(DataRow data);

    }
}
